package cn.zhuama.org.service.impl;

import cn.zhuama.basic.service.impl.BaseServiceImpl;
import cn.zhuama.basic.util.PageList;
import cn.zhuama.org.domain.Department;
import cn.zhuama.org.mapper.DepartmentMapper;
import cn.zhuama.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void editById(Department department) {
        setDirparth(department);
        departmentMapper.updateById(department);
    }

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.insert(department);//先插入数据，才能得到自己的ID
        setDirparth(department);
        departmentMapper.updateById(department);//纯粹就是为了更新dirparth
    }

    private void setDirparth(Department department) {
        Long parentId = department.getParent_id();
        if(parentId!=null){
            String dirPath = departmentMapper.selectOne(parentId).getDirPath();
            dirPath = dirPath+"/"+ department.getId();
            department.setDirPath(dirPath);
        }else{
            department.setDirPath("/"+ department.getId());
        }
    }

    @Override
    public List<Department> tree() {
        /*1. 所有对象*/
        List<Department> departments = departmentMapper.selectAll();
        /*准备map*/
        Map<Long, Department> map = new HashMap<>();
        /*ID:key   ,deptment：value  map.get(ID)*/
        departments.forEach(department -> {
            map.put(department.getId(),department);
        });
        /*2. 每个一儿子找爹*/
        List<Department> parentList = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id()==null){//无爹，老祖宗
                parentList.add(department);
                continue;
            }
            /*当前department,从他身上拿到了他爹的id*/
            Long parentId = department.getParent_id();
            //Department parent = departmentMapper.selectOne(parentId);//map.get(parentId);
            Department parent = map.get(parentId);
            parent.getChildren().add(department);
        }

        return parentList;
    }
}
